//
// Created by dddgzc on 2025/1/23.
//

#include "Animation.h"

void Animation::setAtlas(Atlas *atlas) {
    this->atlas = atlas;
}

void Animation::reset() {
    this->time = 0;
    this->frameIdx = 0;
    this->interval = 0;
}

void Animation::setInterval(int interval) {
    this->interval = interval;
}

void Animation::setIsLoop(bool isLoop) {
    this->isLoop = isLoop;
}

SDL_Texture *Animation::getFrame() const {
    return atlas->getImage(this->frameIdx);
}

void Animation::setOnAnimationFinishedCallback(std::function<void()> callback) {
    this->onAnimationFinishCallback = callback;
}

int Animation::getIndexFrame() const {
    return frameIdx;
}

bool Animation::checkFinished() const {
    if (isLoop == false && this->frameIdx == atlas->getSize() - 1) {
        return true;
    }
    return false;
}


void Animation::onUpdate(int delta) {
    time += delta;
    if (time >= interval) {
        time = 0;
        frameIdx++;
        if (this->frameIdx >= this->atlas->getSize()) {
            if(this->isLoop == true) {
                this->frameIdx = 0; // 索引回到第一张继续循环
            }else{
                this->frameIdx = this->atlas->getSize() - 1; // 保持在最后一张图
                if (onAnimationFinishCallback != nullptr) {
                    onAnimationFinishCallback();
                }
            }
        }
    }
}

void Animation::onDraw(const Camera& camera,int x, int y) const {
    draw(camera, getFrame(), x, y);
}



